﻿using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using System.Threading;
using Microsoft.Win32;

namespace ManagedFocusApp
{
    /// <summary>
    /// This is a managed version of Microsofts FocusApp of the Hopper package.
    /// Beside the standard focus feature, it provides a simple configuration file
    /// with the following options:
    /// 
    /// line 1: path of application to be focused
    /// line 2: path of the hopper application
    /// line 3: interval of the focus function in milliseconds to be executed
    /// line 4: switch if hopper should start automaticaly
    /// line 5: switch if the history of hopper should be deleted before start
    /// 
    /// developed by Simon Hackfort
    /// 
    /// CodePlex Homepage: http://managedfocusapp.codeplex.com/
    /// Blog: http://www.simonhackfort.net/
    /// </summary>
    static class Program
    {
        [MTAThread]
        static void Main()
        {
            // path of FocusApp
            var focusAppPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);

            // path of HopperApp
            string hopperAppPath;

            // path of focused app
            string focusedAppPath;

            // call interval
            int focusInterval;

            // switch for starting hopper application once
            var hopperStarted = false;

            // switch for deleting old data from registry and the logging directory
            var deleteHopperRegistryEntry = false;

            // check if config file exist
            if (!File.Exists(focusAppPath + "\\ManagedFocusApp.cfg"))
            {
                MessageBox.Show("Error opening ManagedFocusApp.cfg. File not found.", "Error occured", MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                return;
            }

            try
            {
                // get stream to the config file
                var myStreamReader = new StreamReader(focusAppPath + "\\ManagedFocusApp.cfg");
                
                // read path of focused app
                focusedAppPath = myStreamReader.ReadLine();

                // read path of hopper app
                hopperAppPath = myStreamReader.ReadLine();
                
                // read focus interval
                focusInterval = Convert.ToInt32(myStreamReader.ReadLine());

                // read the switch for starting hooper
                if(!Convert.ToBoolean(myStreamReader.ReadLine()))
                    hopperStarted = true;

                // read the switch for clearing hopper history data
                if (Convert.ToBoolean(myStreamReader.ReadLine()))
                    deleteHopperRegistryEntry = true;

                myStreamReader.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error while opening config: " + ex.Message, "Error occured", MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                return;
            }

            try
            {
                // check if focused app exists
                if (!File.Exists(focusedAppPath))
                {
                    MessageBox.Show("Error while open the focused application, File not found.", "Error occured", MessageBoxButtons.OK,
                                               MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                    return;
                }

                // check if focused app exists
                if (!File.Exists(hopperAppPath))
                {
                    MessageBox.Show("error while open the hopper application, File not found.", "Error occured", MessageBoxButtons.OK,
                                               MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                    return;
                }

                // clear hopper history
                if (deleteHopperRegistryEntry)
                {
                    // delete registry entries to avoid info message box on start
                    var hopperRegistryKey = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Hopper");
                    
                    if (hopperRegistryKey != null)
                    {
                        hopperRegistryKey.Close();                        
                        Registry.LocalMachine.DeleteSubKeyTree(@"Software\Microsoft\Hopper");                    
                    }

                    //Directory "\testlog" is always created by Hopper
                    if (Directory.Exists("\\testlog"))
                    {
                        var files = Directory.GetFiles("\\testlog");

                        for (var i = 0; i < files.Length; i++)
                        {
                            //Resetting attributes for deletion
                            new FileInfo(files[i]) { Attributes = FileAttributes.Normal };
                        }

                        Directory.Delete("\\testlog", true);
                    }
                }

                // create process for the focused application
                var processFocusApp = new Process {StartInfo = {FileName = focusedAppPath}};

                while (true)
                {
                    // start process to call focused app by interval
                    //Starting the app during execution brings the app to the foreground
                    processFocusApp.Start();

                    // start hoopper once
                    if (!hopperStarted)
                    {                        
                        hopperStarted = true;

                        // create and start the process for the hopper application
                        var processHopperApp = new Process { StartInfo = { FileName = hopperAppPath } };
                        processHopperApp.Start();
                    }

                    // focus interval
                    Thread.Sleep(focusInterval);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("exception message: " + ex.Message, "Error occured", MessageBoxButtons.OK,
                                MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1);
            }
        
        }
    }
}